<template>
  <div id="art_list">
    <van-pull-refresh
      success-duration="1500"
      :success-text="pullRefresh"
      v-model="isPullLoading"
      @refresh="onRefresh"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >
        <ArticleItem v-for="item in list" :key="item.art_id + ''" :articleItem="item" />
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticleList } from '@/api/article.js'
import { Toast } from 'vant'
import ArticleItem from '@/components/ArticleItem.vue'
export default {
  name: 'ArtcleList',
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      preTimestamp: null,
      error: false,
      isPullLoading: false,
      pullRefresh: ''
    }
  },
  props: {
    channelsId: {
      type: Number,
      required: true
    }
  },
  components: {
    ArticleItem
  },
  // 定义方法
  methods: {
    async onLoad () {
      try {
        // 1. 发送请求获取数据
        const { data: res } = await getArticleList({
          channel_id: this.channelsId,
          timestamp: this.preTimestamp || Date.now(),
          with_top: 1
        })

        // 2. 保存数据
        this.list.push(...res.data.results)
        // 保存时间戳 下次发起请求需要上次的时间戳
        this.preTimestamp = res.data.pre_timestamp
        // 3. 加载状态结束
        this.loading = false
        // 4. 数据全部加载完成
        if (res.data.results.length === 0) {
          // 时间戳为空代表没有数据
          this.finished = true
        }
      } catch (err) {
        Toast.clear()
        this.error = true
        this.loading = false
      }
    },
    async onRefresh () {
      try {
        const { data: res } = await getArticleList({
          channel_id: this.channelsId,
          timestamp: Date.now(),
          with_top: 1
        })
        // console.log(res.data.results)
        this.list.unshift(...res.data.results)
        this.isPullLoading = false
        this.pullRefresh = '成功，更新' + res.data.results.length + '条数据'
      } catch (err) {
        this.isPullLoading = false
        this.pullRefresh = '刷新失败！'
      }
    }
  }
}
</script>

<style scoped lang="less">
#art_list {
  overflow-y: scroll;
  height: 80vh;
}
</style>
